<!-- 每个回话对应的聊天内容 -->
<script setup lang="ts">
import type { BubbleListInstance } from 'vue-element-plus-x/types/BubbleList';
import type { MessageItem } from './chat';
// no local BubbleProps/ThinkingStatus usage after refactor
// import { FilesCard, Sender, Thinking, Attachments, XMarkdown, BubbleList } from 'vue-element-plus-x';
import { useRoute } from 'vue-router';
import { 
  Refresh, 
  Search, 
  Star, 
  DocumentCopy, 
  Download, 
  Edit, 
  Share, 
  VideoPlay, 
  Tools,
  ArrowLeftBold,
  ArrowRightBold
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { copyHandle, copyMarkdownAsText, copyCodeBlock } from '@/utils/copy';
import { getWorkflowMessages } from '@/api/chat/workflow';
import agentAvatar from '@/assets/images/logo.png';
import userAvatar from '@/assets/images/user.png';
import AgentSelect from '@/components/AgentSelect/index.vue';
import DeepThinkingToggle from '@/components/DeepThinkingToggle/index.vue';
import FilesSelect from '@/components/FilesSelect/index.vue';
import { chatService } from '@/services/chatService';
import { useAppStore } from '@/stores/modules/app';
import { useChatStore } from '@/stores/modules/chat';
import { useFilesStore } from '@/stores/modules/files';
import { useAgentStore } from '@/stores/modules/agent';
import { useUserStore } from '@/stores/modules/user';
import { buildChatHandlers } from './chat';
// 使用 FilesCard 内置文件类型图标

// types moved to chat.ts and imported above

const route = useRoute();
const chatStore = useChatStore();
const filesStore = useFilesStore();
const userStore = useUserStore();
const appStore = useAppStore();
const agentStore = useAgentStore();

// 用户头像
const avatar = computed(() => {
  const userInfo = userStore.userInfo;
  return userInfo?.avatar || userAvatar;
});

// 确保聊天服务有正确的用户信息
watchEffect(() => {
  const username = userStore.userInfo?.username || 'guest';
  if (username) {
    chatService.setUser(username);
  }
});

const inputValue = ref('');
const senderRef = ref<InstanceType<typeof Sender> | null>(null);
const bubbleItems = ref<MessageItem[]>([]);
const bubbleListRef = ref<BubbleListInstance | null>(null);

const isLoading = ref(false);

// 结果展示区域宽度控制
const resultWidth = ref(80); // 默认80%宽度

// 当前选中的智能体
const currentAgent = computed(() => agentStore.currentAgent?.name || '通用智能体');

// 组合业务逻辑 - 从 chat.ts 抽离
const {
  initResultWidth,
  // splitThink,
  loadConversationById,
  startSSE,
  cancelSSE,
  handleDeleteCard,
  scrollToBottom,
} = buildChatHandlers({
  chatService,
  filesStore,
  userStore,
  appStore,
  chatStore,
  getWorkflowMessages,
  agentAvatar,
  getUserAvatar: () => avatar.value as string,
  bubbleItems,
  bubbleListRef,
  inputValue,
  isLoading,
  resultWidth,
  currentAgent,
});

// 初始化结果宽度
initResultWidth();

watch(
  () => route.params?.id,
  async (_id_) => {
    if (_id_) {
      if (_id_ !== 'not_login') {
        // 判断的当前会话id是否有聊天记录，有缓存则直接赋值展示
        const existingChats = chatStore.chatMap[`${_id_}`];
        if (existingChats && Array.isArray(existingChats) && existingChats.length > 0) {
          bubbleItems.value = existingChats as MessageItem[];
          // 设置会话ID到chatService
          chatService.setConversationId(String(_id_));
          // 滚动到底部
          nextTick(scrollToBottom);
          return;
        }

        await loadConversationById(String(_id_));

        // 滚动到底部
        nextTick(scrollToBottom);
      }

      // 如果本地有发送内容 ，则直接发送
      const v = localStorage.getItem('chatContent');
      if (v) {
        // 发送消息
        console.log('发送消息 v', v);
        nextTick(() => {
          startSSE(v);
        });

        localStorage.removeItem('chatContent');
      }
    } else {
      // 新建会话：清空聊天记录和会话ID
      bubbleItems.value = [];
      chatService.createNewConversation();
    }
  },
  { immediate: true, deep: true },
);

// 以上方法均来自 buildChatHandlers

watch(
  () => filesStore.filesList?.length || 0,
  (val) => {
    if (val > 0) {
      nextTick(() => {
        senderRef.value?.openHeader();
      });
    }
    else {
      nextTick(() => {
        senderRef.value?.closeHeader();
      });
    }
  },
);

// 按钮点击处理函数
const handleRegenerate = (item: MessageItem) => {
  console.log('重新生成:', item);
  ElMessage.info('重新生成功能');
};

const handleSearch = (item: MessageItem) => {
  console.log('搜索相关:', item);
  ElMessage.info('搜索相关功能');
};

const handleFavorite = (item: MessageItem) => {
  console.log('收藏:', item);
  ElMessage.success('已收藏');
};

const handleCopy = async (item: MessageItem) => {
  if (!item.content) {
    ElMessage.warning('没有可复制的内容');
    return;
  }

  // 如果是系统消息（AI回复），通常是Markdown格式，提供选择
  if (item.role === 'system') {
    // 可以根据需要选择复制原始Markdown还是纯文本
    await copyMarkdownAsText(item.content);
  } else {
    // 用户消息直接复制
    await copyHandle(item.content);
  }
};

// 文档处理智能体按钮处理
const handleCopyDocument = async (item: MessageItem) => {
  console.log('复制文档:', item);
  await handleCopy(item);
};

const handleDownloadDocument = (item: MessageItem) => {
  console.log('下载文档:', item);
  ElMessage.info('下载文档功能');
};

const handleEditDocument = (item: MessageItem) => {
  console.log('编辑文档:', item);
  ElMessage.info('编辑文档功能');
};

const handleShareDocument = (item: MessageItem) => {
  console.log('分享文档:', item);
  ElMessage.info('分享文档功能');
};

// 代码助手智能体按钮处理
const handleCopyCode = async (item: MessageItem) => {
  console.log('复制代码:', item);
  // 对于代码内容，直接复制原始内容
  if (item.content) {
    await copyHandle(item.content);
  }
};

const handleRunCode = (item: MessageItem) => {
  console.log('运行代码:', item);
  ElMessage.info('运行代码功能');
};

const handleDebugCode = (item: MessageItem) => {
  console.log('调试代码:', item);
  ElMessage.info('调试代码功能');
};

const handleDownloadCode = (item: MessageItem) => {
  console.log('下载代码:', item);
  ElMessage.info('下载代码功能');
};

// 处理Markdown中代码块的复制
const handleCopyCodeBlock = async (code: string, language?: string) => {
  console.log('复制代码块:', { code, language });
  await copyHandle(code);
};
</script>

<template>
  <div class="chat-with-id-container" :style="{ maxWidth: `${resultWidth}%` }">
    <div class="chat-warp">
      <BubbleList ref="bubbleListRef" :list="bubbleItems" max-height="calc(100vh - 240px)">
        <template #header="{ item }">
          <!-- 使用库内置 Thinking 组件，支持状态样式、折叠与自动收起 -->
          <!-- :model-value="!item.thinlCollapse" -->
          <Thinking v-if="item.reasoning_content" :status="item.thinkingStatus || 'start'"
            :content="item.reasoning_content" button-width="210px" max-width="100%"
            @update:model-value="(val: boolean) => (item.thinlCollapse = !val)"
            @change="(p: any) => (item.thinlCollapse = !p.value)">
            <template #label="{ status }">
              <span>已深度思考<span v-if="status === 'end' && item.thinkingTime">(用时{{ item.thinkingTime }}秒)</span></span>
            </template>
          </Thinking>
        </template>

        <template #content="{ item }">
          <!-- chat 内容走 markdown -->
          <XMarkdown 
            v-if="item.content && item.role === 'system'" 
            :markdown="item.content" 
            class="markdown-body"
            :themes="{ light: 'github-light', dark: 'github-dark' }" 
            default-theme-mode="light"
            @copy-code="handleCopyCodeBlock"
          />
          <!-- 附件列表（仅当有附件时显示，不展示超链接，仅展示类型图标+名称+大小） -->
          <div v-if="item.attachments && item.attachments.length" class="attachments">
            <template v-for="att in item.attachments" :key="att.name">
              <FilesCard :name="att.name" :file-size="att.size" :url="att.url" icon-size="24px" description=" " :style="{
                height: '32px',
                gap: '2px',
                background: '#fff',
                padding: '2px',
                alignItems: 'center',
                marginBottom: '6px',
              }" />
            </template>
          </div>
          <!-- user 内容 纯文本 -->
          <div v-if="item.content && item.role === 'user'" class="user-content">
            {{ item.content }}
          </div>
        </template>

        <!-- 自定义底部 - 仅对AI回答显示 -->
        <template #footer="{ item }">
          <div v-if="item.role === 'system'" class="footer-wrapper">
            <div class="footer-container">
              <!-- 通用智能体按钮 -->
              <template v-if="!item.agent || item.agent === '通用智能体'">
                <el-button type="info" :icon="Refresh" size="small" circle title="重新生成" @click="handleRegenerate(item)" />
                <el-button type="success" :icon="Search" size="small" circle title="搜索相关" @click="handleSearch(item)" />
                <el-button type="warning" :icon="Star" size="small" circle title="收藏" @click="handleFavorite(item)" />
                <el-button color="#626aef" :icon="DocumentCopy" size="small" circle title="复制" @click="handleCopy(item)" />
              </template>
              
              <!-- 文档处理智能体按钮 -->
              <template v-else-if="item.agent === '文档处理智能体'">
                <el-button type="primary" :icon="DocumentCopy" size="small" circle title="复制文档" @click="handleCopyDocument(item)" />
                <el-button type="success" :icon="Download" size="small" circle title="下载文档" @click="handleDownloadDocument(item)" />
                <el-button type="warning" :icon="Edit" size="small" circle title="编辑文档" @click="handleEditDocument(item)" />
                <el-button color="#626aef" :icon="Share" size="small" circle title="分享文档" @click="handleShareDocument(item)" />
              </template>
              
              <!-- 代码助手智能体按钮 -->
              <template v-else-if="item.agent === '代码助手智能体'">
                <el-button type="primary" :icon="DocumentCopy" size="small" circle title="复制代码" @click="handleCopyCode(item)" />
                <el-button type="success" :icon="VideoPlay" size="small" circle title="运行代码" @click="handleRunCode(item)" />
                <el-button type="warning" :icon="Tools" size="small" circle title="调试代码" @click="handleDebugCode(item)" />
                <el-button color="#626aef" :icon="Download" size="small" circle title="下载代码" @click="handleDownloadCode(item)" />
              </template>
              
              <!-- 其他智能体默认按钮 -->
              <template v-else>
                <el-button type="info" :icon="Refresh" size="small" circle title="重新生成" @click="handleRegenerate(item)" />
                <el-button type="success" :icon="Search" size="small" circle title="搜索相关" @click="handleSearch(item)" />
                <el-button type="warning" :icon="Star" size="small" circle title="收藏" @click="handleFavorite(item)" />
                <el-button color="#626aef" :icon="DocumentCopy" size="small" circle title="复制" @click="handleCopy(item)" />
              </template>
            </div>
            <div class="footer-time">
              {{ new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) }}
            </div>
          </div>
        </template>
      </BubbleList>

      <Sender ref="senderRef" v-model="inputValue" class="chat-defaul-sender"
        placeholder="我可以帮你处理各类文档的工作，例如内容提炼、AI润色、文档对比等，请把你的任务交给我吧~" :auto-size="{
          maxRows: 6,
          minRows: 2,
        }" variant="updown" clearable allow-speech :loading="isLoading" @submit="startSSE" @cancel="cancelSSE">
        <template #header>
          <div class="sender-header p-12px pt-6px pb-0px">
            <Attachments :items="filesStore.filesList" :hide-upload="true" @delete-card="handleDeleteCard">
              <template #prev-button="{ show, onScrollLeft }">
                <div v-if="show"
                  class="prev-next-btn left-8px flex-center w-22px h-22px rounded-8px border-1px border-solid border-[rgba(0,0,0,0.08)] c-[rgba(0,0,0,.4)] hover:bg-#f3f4f6 bg-#fff font-size-10px"
                  @click="onScrollLeft">
                  <el-icon>
                    <ArrowLeftBold />
                  </el-icon>
                </div>
              </template>

              <template #next-button="{ show, onScrollRight }">
                <div v-if="show"
                  class="prev-next-btn right-8px flex-center w-22px h-22px rounded-8px border-1px border-solid border-[rgba(0,0,0,0.08)] c-[rgba(0,0,0,.4)] hover:bg-#f3f4f6 bg-#fff font-size-10px"
                  @click="onScrollRight">
                  <el-icon>
                    <ArrowRightBold />
                  </el-icon>
                </div>
              </template>
            </Attachments>
          </div>
        </template>
        <template #prefix>
          <div class="flex-1 flex items-center gap-8px flex-none w-fit flex-wrap">
            <FilesSelect />
            <!-- <ModelSelect /> -->
            <AgentSelect />
            <DeepThinkingToggle />
          </div>
        </template>
      </Sender>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import './chat';
</style>
